import 'dart:async';
import 'dart:convert';
import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:method_info_generator/builder.dart';
import 'package:json_generator/builder.dart';
import 'package:source_gen/builder.dart';

import 'package:build_runner/build_runner.dart' as build_runner;




Future<BuildResult> sourceGenBuild(List<String> arguments) async {
  if (arguments.isEmpty) {
    // Globbing may produce an empty argument list, and it might be ok,
    // but we should give at least notify the caller.
    print('sourceGen_builder: No arguments given, exiting.');
    return BuildResult(BuildStatus.success, []);
  } else {
    // TODO(eernst) feature: We should support some customization of
    // the settings, e.g., specifying options like `suppress_warnings`.
    var options = BuilderOptions(
        <String, dynamic>{'entry_points': arguments, 'formatted': true},
        isRoot: true);
    final builder = methodInfo(options);
    final builder1 = json(options);
    var builders = <BuilderApplication>[
      applyToRoot(builder, generateFor: InputSet(include: arguments), hideOutput: true),
      applyToRoot(builder1, generateFor: InputSet(include: arguments), hideOutput: true),
      applyToRoot(CombiningBuilder(), generateFor: InputSet(include: arguments)),
    ];
    var packageGraph = await PackageGraph.forThisPackage();
    var environment = OverrideableEnvironment(IOEnvironment(packageGraph));
    var buildOptions = await BuildOptions.create(
      LogSubscription(environment),
      deleteFilesByDefault: true,
      packageGraph: packageGraph,
    );
    try {
      var build = await BuildRunner.create(
          buildOptions, environment, builders, const {},
          isReleaseBuild: false);
      var result = await build.run(const {});
      await build.beforeExit();
      return result;
    } catch(e) {
      print(e);
      return BuildResult(BuildStatus.failure, []);
    }finally {
      await buildOptions.logListener.cancel();
    }
  }
}

main() async{
  // BuildResult result = await sourceGenBuild(["lib/**.dart"]);
  // print(result);
}


// void run(){
//   final packageGraph = build_runner_core.PackageGraph.forThisPackage();
//   final builders = [
//     build_runner_core.apply(
//       'json_serializable:json_serializable',
//       [json_serializable_builder.jsonPartBuilder()],
//       build_runner_core.toAllPackages(),
//     ),
//   ];
//
//   final options = build_runner_core.BuildOptions(
//     deleteFilesByDefault: true,
//   );
//
//   final result = await BuildRunner.run(
//     builders,
//     packageGraph,
//     options,
//   );
//
//   if (result.isSuccess) {
//     print('Build completed successfully');
//   } else {
//     print('Build failed');
//   }
// }